package com.haoji.upload.common.exception;

import com.haoji.upload.common.constant.Constant;
import com.haoji.upload.common.constant.ResponseEnum;
import com.haoji.upload.common.dto.WebResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: upload
 * @description: 自定义全局异常
 * @author: xiaolei
 * @create: 2021-04-16 17:31
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常统一处理
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    public WebResponse<String> baseExceptionHandler(BaseException ex) {
        WebResponse<String> responseEntity = new WebResponse<String>(ex.getMessage());
        responseEntity.setCode(Constant.N);
        return responseEntity;
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public WebResponse<String> exceptionHandler(HttpServletRequest req, Exception e){
        log.error("接口调用报错：{}", ExceptionUtils.getStackTrace(e));
        return WebResponse.error(ResponseEnum.OTHER_ERROR.getMessage());
    }

}
